package work.flow.demo.config.constant;

import org.flowable.engine.*;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Process {

    private static final Logger logger = LoggerFactory.getLogger(Process.class);

    @Bean(name = {"Process"})
    public ProcessEngine processEngine() {
        logger.warn("=======>processEngine初始化了<=======");
        // 1. 初始化流程引擎
        ProcessEngineConfiguration config = ProcessEngineConfiguration
                .createStandaloneProcessEngineConfiguration()
                .setJdbcUrl("jdbc:postgresql://172.26.2.97:5432/test_02?useSSL=true&serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8")
                .setJdbcUsername("postgres")
                .setJdbcPassword("abc123456")
                .setJdbcDriver("org.postgresql.Driver")
                .setDatabaseSchemaUpdate(ProcessEngineConfiguration.DB_SCHEMA_UPDATE_TRUE);
        ProcessEngine processEngine = config.buildProcessEngine();

        // 2. 部署流程定义
        RepositoryService repositoryService = processEngine.getRepositoryService();
        try {
            // 部署流程定义文件
            Deployment deployment = repositoryService.createDeployment().addInputStream(
                    "test03.bpmn20.xml", new FileInputStream("D:/process/test03.bpmn20.xml"))
                    .name("测试流程部署").deploy();
            System.out.println("流程部署成功，部署ID: " + deployment.getId());
        } catch (IOException e) {
            System.out.println("流程实例启动失败: " + e.getMessage());
        }



        //启动流程监测
        RuntimeService runtimeService = processEngine.getRuntimeService();

        // 启动流程实例（使用流程定义key，即bpmn文件中的process id）
        ProcessInstance processInstance  = runtimeService
                .startProcessInstanceByKey("test_003");// "test01"应替换为你的流程ID

        System.out.println("流程实例启动成功，实例ID: " + processInstance.getId());

        // 4. 查询并处理任务
        //queryAndCompleteTasks(processEngine, processInstance);
        TaskService taskService = processEngine.getTaskService();
        // 1. 创建任务查询
        String processInstanceId = processInstance.getId();
        List<Task> tasks = taskService.createTaskQuery()
                .processInstanceId(processInstanceId)  // 按流程实例ID查询
                .taskAssignee("wangwu")                   // 分配人为"a"的任务(对应你BPMN中的flowable:assignee="a")
                .orderByTaskCreateTime().asc()       // 按创建时间排序
                .list();

        // 2. 处理查询结果
        if (tasks.isEmpty()) {
            System.out.println("没有找到待办任务");
        }

        // 3. 获取第一个任务(或使用singleResult()确保只有一个)
        Task task = tasks.get(0);
        System.out.println("找到任务: " + task.getName());
        System.out.println("任务ID: " + task.getId());
        System.out.println("创建时间: " + task.getCreateTime());

        // 4. 完成任务(流转到下一步)
        taskService.complete(task.getId());
        System.out.println("任务已完成，流程已流转");

        // 5. 可以添加流程变量(可选)
        // Map<String, Object> variables = new HashMap<>();
        // variables.put("approvalResult", true);
        // taskService.complete(task.getId(), variables);


        // 5. 关闭引擎（实际应用中通常不需要）
        // processEngine.close();

        return processEngine;
    }
}
